package leetcode;

/**
 * @author yinlei
 * @date 2018/6/19
 * @since 1.0.0
 */
public class N007ReverseInteger {

    public static void main(String[] args) {

        System.out.println(reverse(321));
        System.out.println(reverse(1));
        System.out.println(reverse(0));
        System.out.println(reverse(-123));
        System.out.println(reverse(123));
        System.out.println(reverse(1534236469));
        System.out.println(reverse(-2147483648));
    }

    static public int reverse(int x) {
        int result = 0;
        int last = x;

        while (last != 0) {
            int temp = result * 10 + last % 10;

            // 判断溢出方法
            if (result != temp / 10) {
                return 0;
            }

            result = temp;
            last /= 10;
        }

        return result;
    }

//        int tip = 1;
//        long last = x;
//        if (x < 0) {
//            tip = -1;
//            last = last * tip;
//        }
//        int[] arr = new int[15];
//        int length = 0;
//        do {
//            int yu = (int) (last % 10);
//            arr[length++] = yu;
//            last = last / 10;
//        } while (last > 0);
//
//        long level = 1;
//        long res = 0L;
//        for (int i = length; i > 0; i--) {
//            res += arr[i - 1] * level;
//            level = level * 10;
//        }
//
//        res *= tip;
//
//        // 考虑整数溢出
//        if (res > Integer.MAX_VALUE || res < Integer.MIN_VALUE)
//            return 0;
//
//        return (int) res;
//    }
}
